﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuddyBoots.Greenlight.QC.Common.Patterns.Behaviour.Mediator
{
    /// <summary>
    /// For objects that wish to register as mediator clients
    /// Provides a unique instance identifier and implements
    /// IDisposable to unregister when the object is finished with
    /// </summary>
    public class MediatorListener : IDisposable
    {
        /// <summary>
        /// The instance identifier
        /// </summary>
        private readonly string instanceId = Guid.NewGuid().ToString();

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Gets the instance identifier.
        /// </summary>
        /// <value>
        /// The instance identifier.
        /// </value>
        protected string InstanceId
        {
            get
            {
                return this.instanceId;
            }
        }

        /// <summary>
        /// Releases managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                Mediator.UnregisterAll(this.instanceId);
            }
        }
    }
}
